﻿#include "stdafx.h"
#include "videoUtil.h"

VideoR::VideoR()
{
}

VideoR::~VideoR()
{
	close();
}

bool VideoR::open(int _device)
{
	if (is_opened()) {
		close();
	}
    return cap.open(_device);
}

bool VideoR::open(const string& _file_name)
{
	if (is_opened()) {
		close();
	}
    return cap.open(_file_name);
}

bool VideoR::is_opened()
{
    return cap.isOpened();
}

void VideoR::close()
{
    if(is_opened()){
        cap.release();
    }
}

bool VideoR::get_next_frame(Mat& _img)
{
    if(is_opened()==false){
        return false;
    }
    
    return cap.read(_img);
}

bool VideoR::get_frame(Mat& _img, unsigned int _frame_num)
{
    if(-1==_frame_num){
        return get_next_frame(_img);
    }

    double total_frame_cnt = cap.get(CV_CAP_PROP_FRAME_COUNT);
    if(_frame_num > total_frame_cnt){
        return false;
    }

    bool set_result = cap.set(CV_CAP_PROP_POS_FRAMES, static_cast<double>(_frame_num));
    if(false==set_result){
        return false;
    }

    return get_next_frame(_img);
}

unsigned int VideoR::get_frame_num()
{
    double cur = cap.get(CV_CAP_PROP_POS_FRAMES);
    return static_cast<unsigned int>(cur);
}





#include <sstream>
using namespace std;

int VideoCtl::call_cnt = 0;
const string VideoCtl::wnd_name_pre = "xs-cv-wnd-";

VideoCtl::VideoCtl()
{
    call_cnt++;
    stringstream ss_cnt;
    ss_cnt << call_cnt;
    wnd_name = wnd_name_pre + ss_cnt.str();
    ctl = NULL;
}

VideoCtl::VideoCtl(CWnd* _ctl, int flags)
{
    call_cnt++;
    stringstream ss_cnt;
    ss_cnt << call_cnt;
    wnd_name = wnd_name_pre + ss_cnt.str();
    bind_ctl(_ctl, flags);
}

void VideoCtl::bind_ctl(CWnd* _ctl, int flags)
{
    ctl = _ctl;
    ctl->GetClientRect(&wnd_rect);

    namedWindow(wnd_name, flags);
    resizeWindow(wnd_name, wnd_rect.Width(), wnd_rect.Height());
    
    HWND hWnd = (HWND)cvGetWindowHandle(wnd_name.c_str());
    HWND hParent = ::GetParent(hWnd);
    ::SetParent(hWnd, ctl->m_hWnd);
    ::ShowWindow(hParent, SW_HIDE);

    clear_wnd();
}

void VideoCtl::show_image(const Mat& img, bool resize)
{
	if(img.empty()) {
		return;
	}

	Mat toShow = img;
    if(resize){
		cv::resize(img, toShow, Size(wnd_rect.Width(), wnd_rect.Height()));
    }

    InputArray ia(toShow);

    imshow(wnd_name, ia);
    ctl->UpdateWindow();
}

void VideoCtl::clear_wnd()
{
    CRect rc;
    ctl->GetClientRect(&rc);
    Mat img = Mat::zeros(rc.Height(), rc.Width(), CV_32F);
    InputArray ia(img);
    imshow(wnd_name, ia);
    ctl->UpdateWindow();
}
